package com.example.launibleplugin.utils

import android.bluetooth.BluetoothAdapter
import com.example.launibleplugin.constants.BluetoothConstants
import com.google.gson.Gson

/**
 * 错误类型枚举
 * Function: 定义插件中可能出现的错误类型
 * Note: 用于错误分类和处理
 */
enum class ErrorType(val code: Int, val description: String) {
    // 蓝牙相关错误 (1000-1999)
    BLUETOOTH_NOT_SUPPORTED(1001, "设备不支持蓝牙"),
    BLUETOOTH_NOT_ENABLED(1002, "蓝牙未启用"),
    BLUETOOTH_ADAPTER_NULL(1003, "蓝牙适配器为空"),
    BLUETOOTH_LE_NOT_SUPPORTED(1004, "设备不支持蓝牙低功耗"),
    
    // 权限相关错误 (2000-2999)
    PERMISSION_DENIED(2001, "权限被拒绝"),
    LOCATION_PERMISSION_REQUIRED(2002, "需要位置权限"),
    BLUETOOTH_PERMISSION_REQUIRED(2003, "需要蓝牙权限"),
    
    // 扫描相关错误 (3000-3999)
    SCAN_FAILED_ALREADY_STARTED(3001, "扫描已在进行中"),
    SCAN_FAILED_APPLICATION_REGISTRATION_FAILED(3002, "应用注册失败"),
    SCAN_FAILED_INTERNAL_ERROR(3003, "扫描内部错误"),
    SCAN_FAILED_FEATURE_UNSUPPORTED(3004, "扫描功能不支持"),
    SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES(3005, "硬件资源不足"),
    SCAN_FAILED_SCANNING_TOO_FREQUENTLY(3006, "扫描过于频繁"),
    
    // 连接相关错误 (4000-4999)
    CONNECTION_FAILED_ESTABLISHMENT(4001, "连接建立失败"),
    CONNECTION_TIMEOUT(4002, "连接超时"),
    CONNECTION_LOST(4003, "连接丢失"),
    CONNECTION_REJECTED(4004, "连接被拒绝"),
    DEVICE_NOT_FOUND(4005, "设备未找到"),
    DEVICE_NOT_CONNECTED(4006, "设备未连接"),
    
    // GATT相关错误 (5000-5999)
    GATT_FAILURE(5001, "GATT操作失败"),
    GATT_INSUFFICIENT_AUTHENTICATION(5002, "GATT认证不足"),
    GATT_INSUFFICIENT_ENCRYPTION(5003, "GATT加密不足"),
    GATT_INVALID_HANDLE(5004, "GATT句柄无效"),
    GATT_READ_NOT_PERMITTED(5005, "GATT读取不被允许"),
    GATT_REQUEST_NOT_SUPPORTED(5006, "GATT请求不支持"),
    GATT_WRITE_NOT_PERMITTED(5007, "GATT写入不被允许"),
    
    // 数据相关错误 (6000-6999)
    DATA_PARSING_FAILED(6001, "数据解析失败"),
    DATA_VALIDATION_FAILED(6002, "数据验证失败"),
    DATA_CHECKSUM_MISMATCH(6003, "数据校验和不匹配"),
    DATA_FORMAT_INVALID(6004, "数据格式无效"),
    DATA_SIZE_EXCEEDED(6005, "数据大小超限"),
    
    // 配置相关错误 (7000-7999)
    CONFIGURATION_INVALID(7001, "配置无效"),
    PARAMETER_MISSING(7002, "参数缺失"),
    PARAMETER_INVALID(7003, "参数无效"),
    
    // 系统相关错误 (8000-8999)
    SYSTEM_ERROR(8001, "系统错误"),
    OUT_OF_MEMORY(8002, "内存不足"),
    FILE_IO_ERROR(8003, "文件IO错误"),
    NETWORK_ERROR(8004, "网络错误"),
    
    // 插件相关错误 (9000-9999)
    PLUGIN_NOT_INITIALIZED(9001, "插件未初始化"),
    PLUGIN_ALREADY_INITIALIZED(9002, "插件已初始化"),
    CALLBACK_NOT_SET(9003, "回调未设置"),
    
    // 未知错误
    UNKNOWN_ERROR(9999, "未知错误")
}

/**
 * 错误信息类
 * Function: 封装错误信息
 * Note: 包含错误代码、消息、原因等详细信息
 */
data class ErrorInfo(
    val type: ErrorType,
    val message: String,
    val cause: Throwable? = null,
    val timestamp: Long = System.currentTimeMillis(),
    val context: Map<String, Any> = emptyMap()
) {
    /**
     * Function: 转换为JSON字符串
     * Return: String - JSON格式的错误信息
     * Note: 用于API响应和日志记录
     */
    fun toJson(): String {
        val gson = Gson()
        val errorMap = mapOf(
            "errorCode" to type.code,
            "errorType" to type.name,
            "errorMessage" to message,
            "description" to type.description,
            "timestamp" to timestamp,
            "context" to context,
            "stackTrace" to (cause?.stackTraceToString() ?: "")
        )
        return gson.toJson(errorMap)
    }
    
    /**
     * Function: 获取用户友好的错误消息
     * Return: String - 用户可理解的错误描述
     * Note: 提供简化的错误描述给最终用户
     */
    fun getUserFriendlyMessage(): String {
        return when (type) {
            ErrorType.BLUETOOTH_NOT_SUPPORTED -> "您的设备不支持蓝牙功能"
            ErrorType.BLUETOOTH_NOT_ENABLED -> "请先开启蓝牙功能"
            ErrorType.PERMISSION_DENIED -> "请授予必要的权限"
            ErrorType.LOCATION_PERMISSION_REQUIRED -> "需要位置权限才能扫描蓝牙设备"
            ErrorType.DEVICE_NOT_FOUND -> "未找到指定的设备"
            ErrorType.CONNECTION_TIMEOUT -> "设备连接超时，请重试"
            ErrorType.CONNECTION_LOST -> "设备连接已断开"
            ErrorType.DATA_PARSING_FAILED -> "数据解析失败，请检查设备"
            else -> type.description
        }
    }
}

/**
 * 错误处理器
 * Function: 统一的错误处理和报告机制
 * Note: 提供错误分类、日志记录、用户通知等功能
 */
object ErrorHandler {
    
    private const val TAG = "ErrorHandler"
    private val errorHistory = mutableListOf<ErrorInfo>()
    private const val MAX_ERROR_HISTORY = 100
    
    /**
     * Function: 处理错误
     * Parameter: errorType - 错误类型
     * Parameter: message - 错误消息
     * Parameter: cause - 异常原因
     * Parameter: context - 错误上下文
     * Return: ErrorInfo - 错误信息对象
     * Note: 统一的错误处理入口
     */
    fun handleError(
        errorType: ErrorType,
        message: String = errorType.description,
        cause: Throwable? = null,
        context: Map<String, Any> = emptyMap()
    ): ErrorInfo {
        val errorInfo = ErrorInfo(
            type = errorType,
            message = message,
            cause = cause,
            context = context
        )
        
        // 记录错误日志
        logError(errorInfo)
        
        // 添加到错误历史
        addToErrorHistory(errorInfo)
        
        return errorInfo
    }
    
    /**
     * Function: 处理蓝牙扫描错误
     * Parameter: errorCode - 扫描错误代码
     * Parameter: context - 错误上下文
     * Return: ErrorInfo - 错误信息对象
     * Note: 专门处理蓝牙扫描相关的错误
     */
    fun handleScanError(errorCode: Int, context: Map<String, Any> = emptyMap()): ErrorInfo {
        val errorType = when (errorCode) {
            1 -> ErrorType.SCAN_FAILED_ALREADY_STARTED
            2 -> ErrorType.SCAN_FAILED_APPLICATION_REGISTRATION_FAILED
            3 -> ErrorType.SCAN_FAILED_INTERNAL_ERROR
            4 -> ErrorType.SCAN_FAILED_FEATURE_UNSUPPORTED
            5 -> ErrorType.SCAN_FAILED_OUT_OF_HARDWARE_RESOURCES
            6 -> ErrorType.SCAN_FAILED_SCANNING_TOO_FREQUENTLY
            else -> ErrorType.UNKNOWN_ERROR
        }
        
        return handleError(
            errorType = errorType,
            message = "扫描失败，错误代码: $errorCode",
            context = context + mapOf("scanErrorCode" to errorCode)
        )
    }
    
    /**
     * Function: 处理GATT错误
     * Parameter: status - GATT状态码
     * Parameter: operation - 操作类型
     * Parameter: context - 错误上下文
     * Return: ErrorInfo - 错误信息对象
     * Note: 专门处理GATT操作相关的错误
     */
    fun handleGattError(status: Int, operation: String, context: Map<String, Any> = emptyMap()): ErrorInfo {
        val errorType = when (status) {
            1 -> ErrorType.GATT_FAILURE
            5 -> ErrorType.GATT_INSUFFICIENT_AUTHENTICATION
            15 -> ErrorType.GATT_INSUFFICIENT_ENCRYPTION
            1 -> ErrorType.GATT_INVALID_HANDLE
            2 -> ErrorType.GATT_READ_NOT_PERMITTED
            6 -> ErrorType.GATT_REQUEST_NOT_SUPPORTED
            3 -> ErrorType.GATT_WRITE_NOT_PERMITTED
            else -> ErrorType.GATT_FAILURE
        }
        
        return handleError(
            errorType = errorType,
            message = "GATT操作失败: $operation, 状态码: $status",
            context = context + mapOf(
                "gattStatus" to status,
                "operation" to operation
            )
        )
    }
    
    /**
     * Function: 处理连接错误
     * Parameter: status - 连接状态
     * Parameter: deviceId - 设备ID
     * Parameter: context - 错误上下文
     * Return: ErrorInfo - 错误信息对象
     * Note: 专门处理设备连接相关的错误
     */
    fun handleConnectionError(status: Int, deviceId: String, context: Map<String, Any> = emptyMap()): ErrorInfo {
        val (errorType, errorMessage) = when (status) {
            BluetoothAdapter.STATE_DISCONNECTED -> ErrorType.CONNECTION_LOST to "设备连接丢失"
            133 -> ErrorType.CONNECTION_FAILED_ESTABLISHMENT to "GATT错误 - 连接失败"
            135 -> ErrorType.CONNECTION_FAILED_ESTABLISHMENT to "设备不可达或已关闭"
            8 -> ErrorType.CONNECTION_TIMEOUT to "连接超时"
            19 -> ErrorType.CONNECTION_FAILED_ESTABLISHMENT to "设备未找到"
            22 -> ErrorType.CONNECTION_FAILED_ESTABLISHMENT to "设备忙碌，无法连接"
            129 -> ErrorType.CONNECTION_FAILED_ESTABLISHMENT to "GATT内部错误"
            132 -> ErrorType.CONNECTION_FAILED_ESTABLISHMENT to "连接被设备拒绝"
            134 -> ErrorType.CONNECTION_LOST to "连接意外丢失"
            else -> ErrorType.CONNECTION_FAILED_ESTABLISHMENT to "未知连接错误"
        }
        
        return handleError(
            errorType = errorType,
            message = "设备连接失败: $deviceId - $errorMessage (状态码: $status)",
            context = context + mapOf(
                "deviceId" to deviceId,
                "connectionStatus" to status,
                "errorDescription" to errorMessage
            )
        )
    }
    
    /**
     * Function: 处理权限错误
     * Parameter: permissions - 缺失的权限列表
     * Parameter: context - 错误上下文
     * Return: ErrorInfo - 错误信息对象
     * Note: 专门处理权限相关的错误
     */
    fun handlePermissionError(permissions: Array<String>, context: Map<String, Any> = emptyMap()): ErrorInfo {
        val errorType = when {
            permissions.any { it.contains("LOCATION") } -> ErrorType.LOCATION_PERMISSION_REQUIRED
            permissions.any { it.contains("BLUETOOTH") } -> ErrorType.BLUETOOTH_PERMISSION_REQUIRED
            else -> ErrorType.PERMISSION_DENIED
        }
        
        return handleError(
            errorType = errorType,
            message = "缺少权限: ${permissions.joinToString(", ")}",
            context = context + mapOf("missingPermissions" to permissions.toList())
        )
    }
    
    /**
     * Function: 处理数据解析错误
     * Parameter: data - 原始数据
     * Parameter: reason - 失败原因
     * Parameter: context - 错误上下文
     * Return: ErrorInfo - 错误信息对象
     * Note: 专门处理数据解析相关的错误
     */
    fun handleDataParsingError(data: ByteArray, reason: String, context: Map<String, Any> = emptyMap()): ErrorInfo {
        val errorType = when {
            reason.contains("checksum", ignoreCase = true) -> ErrorType.DATA_CHECKSUM_MISMATCH
            reason.contains("format", ignoreCase = true) -> ErrorType.DATA_FORMAT_INVALID
            reason.contains("size", ignoreCase = true) -> ErrorType.DATA_SIZE_EXCEEDED
            else -> ErrorType.DATA_PARSING_FAILED
        }
        
        return handleError(
            errorType = errorType,
            message = "数据解析失败: $reason",
            context = context + mapOf(
                "dataSize" to data.size,
                "dataHex" to data.joinToString(" ") { "%02X".format(it) },
                "reason" to reason
            )
        )
    }
    
    /**
     * Function: 记录错误日志
     * Parameter: errorInfo - 错误信息
     * Note: 将错误信息记录到日志系统
     */
    private fun logError(errorInfo: ErrorInfo) {
        val logMessage = "[${errorInfo.type.name}] ${errorInfo.message}"
        
        when (errorInfo.type.code) {
            in 1000..3999 -> Logger.w(TAG, logMessage, errorInfo.cause)
            in 4000..6999 -> Logger.e(TAG, logMessage, errorInfo.cause)
            in 7000..8999 -> Logger.e(TAG, logMessage, errorInfo.cause)
            else -> Logger.e(TAG, logMessage, errorInfo.cause)
        }
        
        // 记录详细的错误上下文
        if (errorInfo.context.isNotEmpty()) {
            Logger.d(TAG, "错误上下文: ${errorInfo.context}")
        }
    }
    
    /**
     * Function: 添加到错误历史
     * Parameter: errorInfo - 错误信息
     * Note: 维护错误历史记录，用于问题诊断
     */
    private fun addToErrorHistory(errorInfo: ErrorInfo) {
        synchronized(errorHistory) {
            errorHistory.add(errorInfo)
            
            // 保持历史记录数量在限制范围内
            if (errorHistory.size > MAX_ERROR_HISTORY) {
                errorHistory.removeAt(0)
            }
        }
    }
    
    /**
     * Function: 获取错误历史
     * Parameter: limit - 返回数量限制
     * Return: List<ErrorInfo> - 错误历史列表
     * Note: 获取最近的错误记录
     */
    fun getErrorHistory(limit: Int = 20): List<ErrorInfo> {
        synchronized(errorHistory) {
            return errorHistory.takeLast(limit)
        }
    }
    
    /**
     * Function: 清除错误历史
     * Note: 清空错误历史记录
     */
    fun clearErrorHistory() {
        synchronized(errorHistory) {
            errorHistory.clear()
        }
    }
    
    /**
     * Function: 获取错误统计
     * Return: Map<String, Any> - 错误统计信息
     * Note: 返回错误类型分布等统计数据
     */
    fun getErrorStats(): Map<String, Any> {
        synchronized(errorHistory) {
            val stats = mutableMapOf<String, Any>()
            
            stats["totalErrors"] = errorHistory.size
            
            // 按错误类型统计
            val typeStats = errorHistory.groupBy { it.type.name }
                .mapValues { it.value.size }
            stats["errorsByType"] = typeStats
            
            // 最近24小时的错误数量
            val last24Hours = System.currentTimeMillis() - 24 * 60 * 60 * 1000
            val recentErrors = errorHistory.count { it.timestamp > last24Hours }
            stats["errorsLast24Hours"] = recentErrors
            
            return stats
        }
    }
    
    /**
     * Function: 创建错误响应
     * Parameter: errorInfo - 错误信息
     * Return: String - JSON格式的错误响应
     * Note: 创建统一格式的错误响应
     */
    fun createErrorResponse(errorInfo: ErrorInfo): String {
        val gson = Gson()
        val response = mapOf(
            "success" to false,
            "error" to mapOf(
                "code" to errorInfo.type.code,
                "type" to errorInfo.type.name,
                "message" to errorInfo.getUserFriendlyMessage(),
                "details" to errorInfo.message,
                "timestamp" to errorInfo.timestamp
            )
        )
        return gson.toJson(response)
    }
}